<template>
  <div class="flexContent">
    <div class="searchBox">

      <el-form class="demo-form-inline" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="用户名">
                  <el-input v-clearEmoji v-model.trim="employeeName" clearable style="width: 95%" placeholder="用户名/员工姓名"
                    @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="所属部门">
                  <el-select v-model="deptId" filterable clearable popper-class="eloption" style="width: 95%"
                    @click.native="getDeptListEasy">
                    <el-option v-for="dept in deptList" :key="dept.id" :value="dept.id" :label="dept.deptName" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" v-has="'userInfo_add'" @click="addFn">新增</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <el-table border class="tablebox" :data="userList" style="width: 100%" height="100%" size="medium">
          <el-table-column type="index" align="center" width="80" label="序号" />
          <el-table-column prop="userName" align="center" label="用户名" />
          <el-table-column prop="employeeName" align="center" label="员工姓名" />
          <el-table-column prop="deptName" align="center" label="所属部门" />
          <el-table-column prop="phone" align="center" label="电话" />
          <el-table-column align="center" label="更新时间">
            <template v-slot="{ row }">
              {{ row.updateTime | parseTime }}
            </template>
          </el-table-column>
          <el-table-column v-if="$showFn(['userInfo_detail', 'userInfo_edit', 'userInfo_del'])" align="center"
            fixed="right" width="250" label="操作">
            <template v-slot="{ row }">
              <el-button type="text" style="margin-right: 10px; color: rgb(0, 132, 255)" @click.stop="getDetail(row)"
                v-has="'userInfo_detail'">详情</el-button>
              <el-button slot="reference" v-if="row.isFlag === '0'" style="color: rgb(0, 132, 255)" type="text"
                @click.stop="edit(row)" v-has="'userInfo_edit'">修改</el-button>
              <el-button type="text" v-if="row.isFlag === '0'" style="margin-right: 10px; color: red"
                @click="resetPwdFn(row)" v-has="'reset_pwd'">重置密码</el-button>
              <el-button type="text" v-if="row.isFlag === '0'" style="margin-right: 10px; color: red"
                @click="$delFn('用户', del, row)" v-has="'userInfo_del'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,-> , sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <AddDialog :close-on-click-modal="false" :show-dialog.sync="showDialog" :title="title" @btnOk="btnOk" @close="close">
      <el-form ref="addFormRef" :disabled="title === '详情'" :model="addForm" :rules="addRules" label-width="100px">
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-clearEmoji v-model.trim="addForm.employeeName" placeholder="请输入..." />
        </el-form-item>
        <el-form-item label="账号" prop="userName">
          <el-input v-clearEmoji v-model.trim="addForm.userName" :disabled="title === '修改'" placeholder="请输入..." />
        </el-form-item>
        <el-form-item label="密码" prop="password2" v-if="title === '新增'">
          <el-input v-clearEmoji v-model.trim="addForm.password2" placeholder="请输入..." />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-select v-model="addForm.deptId" filterable popper-class="eloption" placeholder="请选择...">
            <el-option v-for="dept in deptList" :key="dept.id" :value="dept.id" :label="dept.deptName" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-clearEmoji v-model.trim="addForm.phone" placeholder="请输入..." />
        </el-form-item>
        <el-form-item label="角色" prop="roleIdList">
          <el-select v-model="addForm.roleIdList" multiple popper-class="eloption" filterable placeholder="请选择...">
            <el-option v-for="item in roleList" :key="item.id" :value="item.id" :label="item.roleName" />
          </el-select>
        </el-form-item>
      </el-form>
    </AddDialog>
    <!-- <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="30%">
      <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="100px">
        <el-form-item label="新密码" prop="pwd">
          <el-input v-clearEmoji v-model="pwdForm.pwd" placeholder="请输入..." />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="celBtn" @click="dialogFormVisible = false">取 消</el-button>
        <el-button class="addBtn" @click.stop="updatePwd">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import md5 from "md5";
import AddDialog from "@/components/Goods/AddDialog";
import {
  getDeptListEasy,
  addUserInfo,
  getUSerList,
  updateUserInfo,
  deleteUserInfo,
  getRoleListEasy,
  resetUserPassword,
  getRoleListAdmin
} from "@/api/system";
export default {
  name: "UserInfo",
  components: {
    AddDialog,
  },
  data() {
    return {
      width: "40%",
      title: "新增",
      showDialog: false,
      dialogFormVisible: false,
      addForm: {
        userName: "",
        phone: "",
        roleIdList: [],
        deptId: "",
        password2: "",
        employeeName: "",
        // storeManage: "0",
      },
      pwdForm: {
        pwd: "",
      },
      pwdRules: {
        pwd: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 16,
            message: "长度在6到16个字符",
            trigger: "change",
          },
          {
            pattern: /^[A-Za-z0-9]+$/,
            message: "请输入数字或字母",
            trigger: "change",
          },
        ],
      },
      addRules: {
        userName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            pattern:
              /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: "用户名应为手机号格式",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern:
              /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        employeeName: [
          {
            required: true,
            message: "请输入员工姓名",
            trigger: "change",
          },
          {
            min: 1,
            max: 10,
            message: "长度在1到10个字符",
            trigger: "change",
          }
        ],
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "blur",
          },
        ],
        roleIdList: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change",
          },
        ],
        // storeManage: [
        //   {
        //     required: true,
        //     message: "请选择该用户是否为超管",
        //     trigger: "change",
        //   },
        // ],
        password2: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 16,
            message: "长度在6到16个字符",
            trigger: "blur",
          },
          {
            pattern: /^[A-Za-z0-9]+$/,
            message: "请输入数字或字母",
            trigger: "blur",
          },
        ],
      },
      deptList: [],
      roleList: [],
      deptId: "",
      employeeName: "",
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      isSearch: false,
      userList: [],
      userId: "",
    };
  },
  created() {
    // this.getDeptListEasy();
    this.getUserList();
    this.getRoleListEasy();
    // console.log(md5('12345678'))
  },
  methods: {
    async getUserList() {
      const serData = {
        employeeName: this.employeeName ? this.employeeName : "",
        deptId: this.deptId ? this.deptId : "",
      };
      if (!this.isSearch) {
        const serData = {
          employeeName: "",
          deptId: "",
        };
      }
      const res = await getUSerList({ ...this.page, ...serData });
      if (res.code === 200) {
        console.log(res);
        const result = res.data;
        console.log(result);
        this.userList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        console.log("userList", this.userList);
      } else {
        // // this.$message.error(res.message)
      }
    },
    async getDeptListEasy() {
      const res = await getDeptListEasy(this.page);
      if (res.code === 200) {
        console.log(res);
        const result = res.data;
        this.deptList = result;
        console.log("deptList", this.deptList);
      } else {
        // // this.$message.error(res.message)
      }
    },
    async getRoleListEasy() {
      let res = await getRoleListEasy();;
      if (res.code === 200) {
        console.log(res);
        this.roleList = res.data;
        console.log("roleList", this.roleList);
      } else {
        // // this.$message.error(res.message)
      }
    },
    async getRoleListdetail() {
      let res = await getRoleListAdmin();;
      if (res.code === 200) {
        console.log(res);
        this.roleList = res.data;
        console.log("roleList", this.roleList);
      } else {
        // // this.$message.error(res.message)
      }
    },
    addFn() {
      this.title = "新增";
      this.showDialog = true;
      this.getDeptListEasy();
      this.getRoleListEasy();
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      this.getUserList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.getUserList();
    },
    close() {
      console.log("close");
      this.showDialog = false;
      this.addForm = {
        userName: "",
        phone: "",
        roleIdList: "",
        deptId: "",
        password2: "",
        employeeName: "",
      };
      this.$refs.addFormRef.resetFields();
    },
    btnOk() {
      // 判断是新增还是修改
      // const password = md5(this.addForm.password)
      if (this.title === "新增") {
        // 新增
        this.$refs.addFormRef.validate(async (isOk) => {
          if (isOk) {
            //
            const password = md5(this.addForm.password2);
            const res = await addUserInfo({
              ...this.addForm,
              password: password,
            });
            if (res.code === 200) {
              this.$message.success("新增成功");
              this.getUserList();
              this.close();
            } else {
              // this.$message.error(res.message);
            }
          } else {
            this.$message.warning("请检查输入信息");
          }
        });
      } else if (this.title === "详情") {
        // 关闭
        this.close();
      } else if (this.title === "修改") {
        // 修改
        this.$refs.addFormRef.validate(async (isOk) => {
          if (isOk) {
            console.log(this.addForm.password2);
            // const password = md5(this.addForm.password2)
            const res = await updateUserInfo({
              ...this.addForm,
              id: this.userId,
            });
            if (res.code === 200) {
              this.$message.success("修改成功");
              this.getUserList();
              this.close();
            } else {
              // this.$message.error(res.message);
            }
          } else {
            this.$message.warning("请检查输入信息");
          }
        });
      }
    },
    async getDetail(row) {
      this.getRoleListdetail();
      this.showDialog = true;
      this.getDeptListEasy();
      // this.getRoleListEasy();
      // this.addForm.password = row.password.md5()
      this.title = "详情";
      console.log(row);
      this.addForm.userName = row.userName;
      this.addForm.phone = row.phone;
      this.addForm.roleIdList = row.roleIdList;
      this.addForm.deptId = row.deptId;
      // this.addForm.password2 = row.password2;
      this.addForm.employeeName = row.employeeName;
    },
    async edit(row) {
      this.title = "修改";
      console.log(row);
      this.getDeptListEasy();
      this.getRoleListEasy();
      this.addForm.userName = row.userName;
      this.addForm.phone = row.phone;
      this.addForm.roleIdList = row.roleIdList;
      this.addForm.deptId = row.deptId;
      // this.addForm.password2 = row.password;
      this.addForm.employeeName = row.employeeName;
      this.showDialog = true;
      // this.addForm = row
      // this.pwdForm.pwd = "";
      this.userId = row.id;
    },
    async del(row) {
      const res = await deleteUserInfo({ id: row.id });
      if (res.code === 200) {
        this.$message.success("删除成功");
        if (this.userList.length === 1 && this.page.pageNum > 1)
          this.page.pageNum--;
        this.getUserList();
      } else {
        // this.$message.error(res.message);
      }
    },
    async searchFn() {
      this.page.pageNum = 1;
      this.page.pageSize = 20;
      this.isSearch = true;
      this.getUserList();
    },
    resetFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = false;
      this.deptId = "";
      this.employeeName = "";
      this.getUserList();
    },
    updatePwd() {
      this.$refs.pwdFormRef.validate((isOk) => {
        if (isOk) {
          this.addForm.password2 = md5(this.pwdForm.pwd);
          this.dialogFormVisible = false;
        } else {
          this.$message.warning("请检查输入信息");
        }
      });
    },
    resetPwdFn(row) {
      // console.log('row', row);
      this.$confirm(`此操作将重置用户密码, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await resetUserPassword({ id: row.id })
          if (res.code === 200) {
            this.$message.success('重置成功')
          }
          console.log('row', row);
        })
        .catch(() => { });
    }
    // selstoreManage() {
    //   console.log(this.addForm.storeManage);
    //   this.addForm.roleIdList = "";
    //   this.getRoleListEasy(this.addForm.storeManage);
    // },
  },
};
</script>

<style lang="scss" scoped></style>
